package com.insight.modules.system.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.constant.CommonConstant;
import com.insight.common.system.query.QueryGenerator;
import com.insight.common.util.ImportExcelUtil;
import com.insight.common.util.oConvertUtils;
import com.insight.modules.system.entity.SysPosition;
import com.insight.modules.system.service.ISysPositionService;
import com.insight.modules.umpPwdManage.entity.UmpPwdManage;
import com.insight.modules.umpPwdManage.service.IUmpPwdManageService;
import com.insight.modules.util.ZipEncryUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 职务表
 * @Author: jeecg-boot
 * @Date: 2019-09-19
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "职务表")
@RestController
@RequestMapping("/sys/position")
public class SysPositionController {

    @Autowired
    private ISysPositionService sysPositionService;

    @Autowired
    private IUmpPwdManageService umpPwdManageService;

    @Autowired
    private ZipEncryUtils zipEncryUtils;

    /**
     * 分页查询职务列表接口
     * 支持按名称、编码、职务等级筛选，分页返回职务数据
     *
     * @param sysPosition  查询条件对象（name, code, postRank）
     * @param pageNo       页码，默认1
     * @param pageSize     每页数量，默认10
     * @param req          Http请求对象，获取额外参数
     * @return             封装了分页数据的Result对象
     */
    @AutoLog(value = "职务管理-分页列表查询")
    @ApiOperation(value = "职务表-分页列表查询", notes = "职务表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SysPosition>> queryPageList(SysPosition sysPosition,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        Result<IPage<SysPosition>> result = new Result<>();
        QueryWrapper<SysPosition> queryWrapper = new QueryWrapper<>();

        // 根据条件构造查询Wrapper，模糊匹配名称和编码，精确匹配职务等级
        if (oConvertUtils.isNotEmpty(sysPosition.getName())) {
            queryWrapper.like("name", sysPosition.getName());
        }
        if (oConvertUtils.isNotEmpty(sysPosition.getCode())) {
            queryWrapper.like("code", sysPosition.getCode());
        }
        if (oConvertUtils.isNotEmpty(sysPosition.getPostRank())) {
            queryWrapper.eq("post_rank", sysPosition.getPostRank());
        }

        // 分页查询
        Page<SysPosition> page = new Page<>(pageNo, pageSize);
        IPage<SysPosition> pageList = sysPositionService.page(page, queryWrapper);

        // 封装结果
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 新增职务信息接口
     *
     * @param sysPosition  职务实体对象，json格式请求体传递
     * @return             操作结果，成功或失败提示
     */
    @AutoLog(value = "职务管理-添加")
    @ApiOperation(value = "职务表-添加", notes = "职务表-添加")
    @PostMapping(value = "/add")
    public Result<SysPosition> add(@RequestBody SysPosition sysPosition) {
        Result<SysPosition> result = new Result<>();
        try {
            if (sysPosition == null || sysPositionService == null){
                return result.error500("参数错误");
            }
            sysPositionService.save(sysPosition);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑职务信息接口
     *
     * @param sysPosition  带修改信息的职务对象
     * @return             操作结果
     */
    @AutoLog(value = "职务管理-编辑")
    @ApiOperation(value = "职务表-编辑", notes = "职务表-编辑")
    @PutMapping(value = "/edit")
    public Result<SysPosition> edit(@RequestBody SysPosition sysPosition) {
        Result<SysPosition> result = new Result<>();
        // 先查询是否存在该职务
        SysPosition sysPositionEntity = sysPositionService.getById(sysPosition.getId());
        if (sysPositionEntity == null) {
            result.error500("未找到对应实体");
        } else {
            // 更新
            boolean ok = sysPositionService.updateById(sysPosition);
            if (ok) {
                result.success("修改成功!");
            }
            // TODO 返回false说明更新失败，具体原因可根据业务需求补充
        }
        return result;
    }

    /**
     * 通过ID删除职务接口
     *
     * @param id 职务ID
     * @return   操作结果
     */
    @AutoLog(value = "职务管理-通过id删除")
    @ApiOperation(value = "职务表-通过id删除", notes = "职务表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            if (StringUtils.isEmpty(id)){
                return Result.error("id 不能为空");
            }
            sysPositionService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除职务接口
     *
     * @param ids  多个职务ID，逗号分隔
     * @return     操作结果
     */
    @AutoLog(value = "职务管理-批量删除")
    @ApiOperation(value = "职务表-批量删除", notes = "职务表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<SysPosition> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<SysPosition> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.sysPositionService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过ID查询职务详细信息接口
     *
     * @param id 职务ID
     * @return   职务实体对象或错误信息
     */
    @AutoLog(value = "职务管理-通过id查询")
    @ApiOperation(value = "职务表-通过id查询", notes = "职务表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SysPosition> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<SysPosition> result = new Result<>();
        SysPosition sysPosition = sysPositionService.getById(id);
        if (sysPosition == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(sysPosition);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出职务数据为Excel文件
     * 支持条件筛选和导出指定选中数据，导出文件支持加密和重命名
     *
     * @param request  Http请求对象，用于获取查询条件和选中数据
     * @param response Http响应对象，写出Excel文件
     * @param sysPosition 查询条件对象
     */
    @AutoLog(value = "职务管理-导出")
    @RequestMapping(value = "/exportXls")
    public void exportXls(HttpServletRequest request, HttpServletResponse response, SysPosition sysPosition) {
        // Step.1 组装查询条件Wrapper
        QueryWrapper<SysPosition> queryWrapper = QueryGenerator.initQueryWrapper(sysPosition, request.getParameterMap());

        // 过滤选中的数据id（逗号分隔）
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            queryWrapper.in("id", selections.split(","));
        }

        // Step.2 查询符合条件的数据列表
        List<SysPosition> pageList = sysPositionService.list(queryWrapper);

        // Step.3 获取压缩密码和配置，生成文件名
        UmpPwdManage zip = umpPwdManageService.getZip();
        String fileName = umpPwdManageService.exportXlsRename("职务管理");

        // Step.4 调用工具类生成带密码的压缩包并写出响应
        zipEncryUtils.zipPwd(response, SysPosition.class, fileName, zip.getZipPwd(), zip.getIsEncry(), pageList);
    }

    /**
     * 通过Excel导入职务数据
     *
     * @param request  包含上传文件的请求
     * @param response 响应对象
     * @return         导入结果，包含成功与失败的条数和错误信息
     * @throws IOException 文件读取异常
     */
    @AutoLog(value = "职务管理-导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest != null ? multipartRequest.getFileMap() : null;

        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;

        if (fileMap != null && !fileMap.isEmpty()) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                MultipartFile file = entity.getValue();
                if (file == null || file.isEmpty()) {
                    continue;
                }
                ImportParams params = new ImportParams();
                params.setTitleRows(2);
                params.setHeadRows(1);
                params.setNeedSave(true);

                try {
                    List<Object> listSysPositions = ExcelImportUtil.importExcel(file.getInputStream(), SysPosition.class, params);
                    if (listSysPositions == null) {
                        errorLines++;
                        continue;
                    }
                    List<String> list = ImportExcelUtil.importDateSave(listSysPositions, ISysPositionService.class, errorMessage, CommonConstant.SQL_INDEX_UNIQ_CODE);
                    errorLines += list != null ? list.size() : 0;
                    successLines += (listSysPositions.size() - errorLines);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    return Result.error("文件导入失败:" + e.getMessage());
                } finally {
                    try {
                        file.getInputStream().close();
                    } catch (Exception e) {
                        log.error("关闭文件流失败", e);
                    }
                }
            }
        }

        return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
    }

    /**
     * 根据职务编码查询职务信息
     *
     * @param code 职务编码，必传
     * @return     查询到的职务实体或错误信息
     */
    @ApiOperation(value = "职务表-通过code查询", notes = "职务表-通过code查询")
    @GetMapping(value = "/queryByCode")
    public Result<SysPosition> queryByCode(@RequestParam(name = "code", required = true) String code) {
        Result<SysPosition> result = new Result<>();
        QueryWrapper<SysPosition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        SysPosition sysPosition = sysPositionService.getOne(queryWrapper);
        if (sysPosition == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(sysPosition);
            result.setSuccess(true);
        }
        return result;
    }
}

